package com.xfxplus.m.Module.reokhttp;


import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

@Module
public class Netcom {
    @Provides
    @Singleton
    public OkHttpClient getOKHttp(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //自定义拦截器实现请求服务器公共参数，并拼接在请求接口url参数中
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        //请求服务器时间参数（重定向URL，mUrl为请求服务器时间的地址）
                        Request requestHeader = chain.request().newBuilder().url("").get().build();
                        try {
                            //发送请求
                            okhttp3.Response response=chain.proceed(requestHeader);
                            //获得服务器响应数据
                            ResponseBody value = response.body();
                            byte[] resp = value.bytes();
                            String serverTimestamp = new String(resp, "UTF-8");
                            //生成随机数，（请求参数）
                            String nonce="";
                            //sha1加密参数
                            //添加公共参数（服务器要求公共参数拼接到请求参数内，所以公共参数并不能放在请求头header里）
                            HttpUrl.Builder builder = request.url()
                                    .newBuilder()
                                    .addQueryParameter("_t",serverTimestamp)
                                    .addQueryParameter("_n",nonce);
                            //重定向url，重置Request，拼接公共参数的请求url
                            Request newRequest= request.newBuilder()
                                    .url(builder.build().url())
                                    .addHeader("Content-Encoding","gzip")
                                    .build();
                            return chain.proceed(newRequest);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(httpLoggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(1000, TimeUnit.SECONDS)
                .writeTimeout(1000, TimeUnit.SECONDS)
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();
        return httpClient;
    }

    @Provides
    @Singleton
    public Retrofit getRetrifit(OkHttpClient okHttpClient){
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl("http://www.baidu.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit;
    }


    @Singleton
    @Provides
    public Apise getapise(Retrofit retrofit){
        return retrofit.create(Apise.class);
    }

}
